package com.fyfeng.testsign;

import java.util.Locale;

import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fyfeng.android.tools.codec.MD5;
import com.fyfeng.android.tools.view.TextViewUtils;

public class AppDetailActivity extends ActionBarActivity {
	
	public static final String ARGS_PACKAGEINFO = "ARGS_PACKAGEINFO";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_detail);
		
		initCreate();
		
	}

	private void initCreate(){
		Intent intent = this.getIntent();
		if(null == intent){
			return;
		}
		
		PackageInfo packageInfo = intent.getParcelableExtra(ARGS_PACKAGEINFO); 
		
		if(null == packageInfo){
			return;
		}
		
		PackageManager pm = this.getPackageManager();
		PackageInfo info =  null;
		try {
			info = pm.getPackageInfo(packageInfo.packageName, PackageManager.GET_SIGNATURES);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(null == info){
			return;
		}
		
		Signature[] signatures = info.signatures;
		
		String sign_md5 = null;
		for(Signature sign: signatures){
			
			sign_md5 = MD5.md5Hex(sign.toByteArray());
			
			if(!TextUtils.isEmpty(sign_md5)){
				sign_md5 = sign_md5.toUpperCase(Locale.CHINA);
				break;
			}
			
		}
		
		
		TextViewUtils.setText(this, R.id.appname, info.applicationInfo.loadLabel(pm).toString());
		ImageView icon = (ImageView)this.findViewById(R.id.appicon);
		icon.setImageDrawable(info.applicationInfo.loadIcon(pm));
		
		TextView textview_packagename = (TextView)this.findViewById(R.id.app_packagename);
		TextView textview_app_sign_md5 = (TextView)this.findViewById(R.id.app_sign_md5);
		textview_packagename.setText(info.packageName);
		textview_app_sign_md5.setText(sign_md5);
		
		final ClipboardManager cm = (ClipboardManager)this.getSystemService(Context.CLIPBOARD_SERVICE);
		
		final String packagename = info.packageName;
		final String md5sign = sign_md5;
		textview_packagename.setOnLongClickListener(new OnLongClickListener(){

			@Override
			public boolean onLongClick(View v) {
				cm.setText(packagename);
				Toast.makeText(getApplicationContext(), packagename+" 复制到剪切板中.", Toast.LENGTH_SHORT).show();
				return true;
			}});
		
		textview_app_sign_md5.setOnLongClickListener(new OnLongClickListener(){

			@Override
			public boolean onLongClick(View v) {
				cm.setText(md5sign);
				Toast.makeText(getApplicationContext(), md5sign+" 复制到剪切板中.", Toast.LENGTH_SHORT).show();
				return true;
			}});
		
	}
	
	
	
	
}
